package com.java.task20.Work3;

public class TicketThread implements Runnable {
    //定义成员变量
    private int ticket;

    public TicketThread() {
    }

    public TicketThread(int ticket) {
        this.ticket = ticket;
    }

    public int getTicket() {
        return ticket;
    }

    public void setTicket(int ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run() {
        while (true) {
            //同步代码块,一个时间内只能有一个线程得到执行
            synchronized (this) {
                notifyAll();//用于唤醒下一个线程
                if (ticket >= 0) {
                    //打印信息
                    System.out.println("线程" + Thread.currentThread().getName() + "取走一张票，还剩:" + ticket + "张");
                    try {
                        //睡眠0.1秒
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticket--;
                    try {
                        wait();//当前线程进入阻塞状态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;//结束循环
                }
            }

        }

    }
}

